package com.icart.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icart.context.HttpUserContext;
import com.icart.context.storage.ContextStorage;
import com.icart.context.storage.SessionContextStorageImpl;
import com.icart.repositories.*;
import org.dom4j.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;


@Controller
@RequestMapping("/item")
public class ItemController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @Autowired
    private CustcarRepository custcarRepository;
    @Autowired
    private CusttcdiscfeeRepository custtcdiscfeeRepository;
    @Autowired
    private CusttcmeteitemRepository custtcmeteitemRepository;
    @Autowired
    private CusttcRepository custtcRepository;
    @Autowired
    private CusttcservitemRepository custtcservitemRepository;
    @Autowired
    private FiIncomefeeRepository incomefeeRepository;
    @Autowired
    private FiprepayfeeRepository fiprepayfeeRepository;
    @Autowired
    private WoinfoRepository woinfoRepository;
    @Autowired
    private WoinfopayRepository woinfopayRepository;

    /*服务项目*/
    @RequestMapping("/item")
    public String item(Model model) {

        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");
        Object openid=request.getSession().getAttribute("openid");
        model.addAttribute("openid",openid);
        if(userContext!=null) {
            Long custid=userContext.getCustid();
            String custcarsql = "select cc.custid,cc.curkilo,cc.regdate,cc.carno,bc.carvol,bc.caryear,cc.custcarid,(select brandlogo from bi_carbrand where brandid=bc.brandid)brandlogo," +
                    "(select carlinename from bi_carline where carlineid=bc.carlineid)carlinename,(select carfactname from bi_carfactory where carfactid=(select carfactid from bi_carline where carlineid=bc.carlineid))carfactname" +
                    " from cu_custcar cc,bi_cardef bc where cc.setdefault=1 and bc.cartypeid=cc.cartype and cc.custid=" + custid;
            List custcar = custcarRepository.createNativeQuery(custcarsql);
            if(custcar.size()!=0){//该用户已经选择了默认车型
                model.addAttribute("custcar",custcar.get(0));
                 /*查出车牌的省份*/
                String sql2="select dictname from sa_db_dictitem where groupid='BI_CARNOHEAD'";
                List list2=custcarRepository.createNativeQuery(sql2);
                model.addAttribute("province",list2);
            } else{
                model.addAttribute("custid",custid);
            }
        }

        String busiid=request.getParameter("busiid");//业务分类
        model.addAttribute("busiid",busiid);
        if(busiid.equals("48")){//如果业务为套餐,跳转到套餐页面
            Date dates=new Date();
            DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String creattime=format.format(dates);//获取当前系统时间

            String dpsql="select * from mk_discpack where limitchn=0 and tctype='tc' and '"+creattime+"' between salestartdate and saleenddate and stat=1";
            List discpack = custcarRepository.createNativeQuery(dpsql);
            String dpsql1="select mk.*,bc.chnname from mk_discpack mk,bi_chn bc where bc.chnid=mk.limitchn and mk.limitchn not in(0) and mk.tctype='tc' and '"+creattime+"' between mk.salestartdate and mk.saleenddate and mk.stat=1";
            List discpack1 = custcarRepository.createNativeQuery(dpsql1);

            model.addAttribute("discpack",discpack);
            model.addAttribute("custid",userContext.getCustid());
            model.addAttribute("discpack1",discpack1);
            return "item/discpack";
        } else {
            String sql="select bs.servitemid,bs.servitemname,bs.chnid,bp.packid " +
                    "from bi_servitem bs,bi_servpackitem b,bi_servpack bp " +
                    "where bs.isbook=1 and b.servitemid=bs.servitemid and b.packid=bp.packid " +
                    "and bp.busiid=bs.busiid and bs.busiid="+busiid;
            List list = custcarRepository.createNativeQuery(sql);
            String countsql="select count(bs.servitemid)as num " +
                    "from bi_servitem bs,bi_servpackitem b,bi_servpack bp " +
                    "where bs.isbook=1 and b.servitemid=bs.servitemid and b.packid=bp.packid " +
                    "and bp.busiid=bs.busiid and bs.busiid="+busiid;
            List count = custcarRepository.createNativeQuery(countsql);
            //查找所有分组(用于判断)
            String sql1="select bp.packid,bp.packname,bp.remark,bb.belongcode  from bi_servpack bp,bi_servpackbelong bb where bp.packid=bb.packid and bp.busiid="+busiid;
            List list1 = custcarRepository.createNativeQuery(sql1);
            //查询所有分组归属
            String sql2="select DISTINCT(bb.belongcode),sa.dictname from bi_servpackbelong bb,bi_servpack bs,sa_db_dictitem sa " +
                    "where sa.dictid=bb.belongcode and sa.groupid='BI_SERVPACKBELONG' and bb.packid=bs.packid and bs.busiid="+busiid;
            List list2 = custcarRepository.createNativeQuery(sql2);
            model.addAttribute("list",list);
            model.addAttribute("count",count.get(0));
            model.addAttribute("list1",list1);
            model.addAttribute("list2",list2);

            return "item/baoyang";
        }
    }

    @RequestMapping(value = "/updatedate",method = RequestMethod.GET)
    @ResponseBody
    public String updatedate() {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");
        if(userContext!=null) {
            Long custid = userContext.getCustid();
            String date = request.getParameter("date");
            int flag = custcarRepository.update(date, custid);
        }
        return "success";
    }

    @RequestMapping(value = "/updatekm",method = RequestMethod.GET)
    @ResponseBody
    public String updatekm() {
        ContextStorage storage=new SessionContextStorageImpl(request);
        HttpUserContext userContext=storage.getUserContext("loginuser");
        if(userContext!=null) {
            Long custid = userContext.getCustid();
            Long km = Long.parseLong(request.getParameter("km"));
            int flag = custcarRepository.updatekm(km, custid);
        }
        return "success";
    }

    @RequestMapping(value = "/paydis/{custcarid}/{tcid}/{data}/{custid}",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String paydis(@PathVariable(name="custcarid") Long custcarid,@PathVariable(name="tcid") Long tcid,@PathVariable(name="data") String data,@PathVariable(name="custid") Long custid) {
        try{
            InputStream is = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = "";
            String xmlString = null;
            StringBuffer inputString = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            xmlString = inputString.toString();
            reader.close();
            System.out.println("----接收到的数据：---" + xmlString);
            JSONObject jsonstring = xmlToJson(inputString.toString());
//            JSONObject json= JSON.parseObject(jsonstring);
            //String appid=json.get("appid")+"";
            //String mch_id=json.get("mch_id")+"";
            if (jsonstring.getString("return_code").equals("SUCCESS")) {
                //支付成功，进行业务操作
                String tradeid = jsonstring.getString("transaction_id");//交易流水号
                Date dates = new Date();
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = format.format(dates);//获取当前系统时间
                String incomeid = String.valueOf(dates.getTime());//获取当前系统时间,暂时用作应收单号
                String prefeeid = String.valueOf(dates.getTime());//获取当前系统时间,暂时用作财务预收单号
                DateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
                Long tcoid = Long.parseLong(format2.format(dates));//客户套餐编号
                woinfoRepository.savewo(data, custcarid, custid, time, time, time, tcid);
                incomefeeRepository.savefi(incomeid, data, custid, custid, time, time, tcid);
                fiprepayfeeRepository.savefi(prefeeid, data, custid, custid, time, tcid);
                woinfopayRepository.savewoin(data, custid, tradeid, time, incomeid, tcid);
                custtcRepository.save(tcoid, custid, time, time, data, tcid);
                custtcdiscfeeRepository.save(tcoid, custid, tcid);
                custtcmeteitemRepository.save(tcoid, custid, tcid);
                custtcservitemRepository.save(tcoid, custid, tcid);
                System.out.println("完成微信支付");
            }
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("手机支付回调通知失败");
            return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }

    @RequestMapping(value = "/checkpaystat")
    @ResponseBody
    public String checkpaystat(){
        String custid=request.getParameter("custid");
        String tcid=request.getParameter("tcid");
        Calendar cal = Calendar. getInstance ();
        cal.add(Calendar.HOUR ,  -1 ) ;
        Date dates = cal.getTime();
        Date date=new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(dates);//获取当前系统时间
        String time2 = format.format(date);//获取当前系统时间
        System.out.println(time);
        System.out.println(time2);
        List list=woinfopayRepository.createNativeQuery("select * from cu_custtc where tcid="+tcid+" and custid="+custid+" and usestartdate between '"+time+"' and '"+time2+"'");
        if(list.size()==0){
            return "0";
        } else {
            return "1";
        }
    }

    private static JSONObject  xmlToJson(String xml) {
        Document doc= null;
        try {
            doc = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        JSONObject json=new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }

    private static void dom4j2Json(Element element, JSONObject json){
        //如果是属性
        for(Object o:element.attributes()){
            Attribute attr=(Attribute)o;
            if(!isEmpty(attr.getValue())){
                json.put("@"+attr.getName(), attr.getValue());
            }
        }
        List<Element> chdEl=element.elements();
        if(chdEl.isEmpty()&&!isEmpty(element.getText())){//如果没有子元素,只有一个值
            json.put(element.getName(), element.getText());
        }

        for(Element e:chdEl){//有子元素
            if(!e.elements().isEmpty()){//子元素也有子元素
                JSONObject chdjson=new JSONObject();
                dom4j2Json(e,chdjson);
                Object o=json.get(e.getName());
                if(o!=null){
                    JSONArray jsona=null;
                    if(o instanceof JSONObject){//如果此元素已存在,则转为jsonArray
                        JSONObject jsono=(JSONObject)o;
                        json.remove(e.getName());
                        jsona=new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if(o instanceof JSONArray){
                        jsona=(JSONArray)o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                }else{
                    if(!chdjson.isEmpty()){
                        json.put(e.getName(), chdjson);
                    }
                }


            }else{//子元素没有子元素
                for(Object o:element.attributes()){
                    Attribute attr=(Attribute)o;
                    if(!isEmpty(attr.getValue())){
                        json.put("@"+attr.getName(), attr.getValue());
                    }
                }
                if(!e.getText().isEmpty()){
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }

    public static boolean isEmpty(String str) {

        if (str == null || str.trim().isEmpty() || "null".equals(str)) {
            return true;
        }
        return false;
    }

    @RequestMapping(value = "/getoid",method = RequestMethod.GET)
    @ResponseBody
    public String getoid() {
        return nextId();
    }

    private static final String HEAD = "GD";

    /** 序列在id中占的位数 */
    private static final long sequenceBits = 26L;

    /** 生成序列的掩码，这里为67108863 (0b11111111111111111111111111=0x3ffffff=67108863) */
    private static final long sequenceMask = -1L ^ (-1L << sequenceBits);

    /** 毫秒内序列(0~67108863) */
    private static long sequence = -1L;

    /** 上次生成ID的时间截 */
    private static long lastTimestamp = -1L;

    public synchronized String nextId() {
        long timestamp = timeGen();

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        if(sequence == -1){
            //初始化序列号
            initSequence(dateFormat.format(timestamp));
            lastTimestamp = timestamp;
        }

        //如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        //如果是同一天生成的，则进行当天内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            //毫秒内序列溢出
            if (sequence == 0) {
                //异常
                throw new RuntimeException(String.format("工单序列溢出"));
            }
        }
        //时间戳改变，当天内序列重置
        else {
            sequence = 1L;
        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;

        //拼接返回workId
        DecimalFormat df = new DecimalFormat("00000000");
        return HEAD + dateFormat.format(new Date(timestamp)) + df.format(sequence);
    }

    /**
     * 返回以毫秒为单位的当前时间
     * @return 当天零点零分零秒(毫秒)
     */
    protected long timeGen() {
        //今天零点零分零秒的毫秒数
        return System.currentTimeMillis()/(1000*3600*24)*(1000*3600*24)- TimeZone.getDefault().getRawOffset();
    }

    /**
     * 初始化当前序列
     */
    protected void initSequence(String day) {
        String curoid = woinfoRepository.findmaxid( HEAD + day + "%");
        if(curoid == null){
            sequence = 0L;
        } else {
            sequence = Long.valueOf(curoid.substring(10));
        }
    }
}